package com.techsun.utils;

import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.jdbc.ConnectionImpl;
import org.apache.log4j.Logger;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;

public class MysqlUtil {
    Logger logger = Logger.getLogger(MysqlUtil.class);
    private static String className = "com.mysql.cj.jdbc.Driver";
    private Connection connection;
    private Statement statement;

    public List<JSONObject> select(String sql) throws SQLException {
        LinkedList<JSONObject> linkedList = new LinkedList<>();
        ResultSet resultSet = statement.executeQuery(sql);
        ResultSetMetaData metaData = resultSet.getMetaData();
        while (resultSet.next()) {
            JSONObject jsonObject = new JSONObject();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                jsonObject.put(metaData.getColumnName(i + 1), resultSet.getObject(metaData.getColumnName(i + 1)));
            }
            linkedList.add(jsonObject);
        }
        resultSet.close();
        return linkedList;
    }

    public void commit() {
        try {
            connection.commit();
        } catch (SQLException throwables) {
            logger.error(String.format("mysql %s connection commit has error", ((ConnectionImpl) connection).getHostPortPair()), throwables);
        }
    }

    public void rollback() {
        try {
            connection.rollback();
        } catch (SQLException throwables) {
            logger.error(String.format("mysql %s connection rollback has error", ((ConnectionImpl) connection).getHostPortPair()), throwables);
        }
    }

    public void execute(String sql) throws SQLException {
        statement.execute(sql);
    }

    public MysqlUtil(String connectionURL) throws SQLException, ClassNotFoundException {
        Class.forName(className);
        connection = DriverManager.getConnection(connectionURL);
        statement = connection.createStatement();
    }

    public MysqlUtil(String connectionURL, Boolean autoCommit) throws SQLException, ClassNotFoundException {
        Class.forName(className);
        connection = DriverManager.getConnection(connectionURL);
        connection.setAutoCommit(autoCommit);
        statement = connection.createStatement();
    }

    public void close() {
        try {
            if (statement != null)
                statement.close();
            if (connection != null)
                connection.close();
        } catch (SQLException throwables) {
            logger.error(String.format("mysql %s close connection has error", ((ConnectionImpl) connection).getHostPortPair()), throwables);
        }
    }
}
